import base64
import random
import smtplib
import string
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from app.config.config import config
from app.settings import env


def gen_email_code():
    list = random.sample(string.ascii_letters+string.digits, 6)
    return ''.join(list)


def send_email(email, code):
    email_name = config[env].email_name
    passwd = config[env].passwd

    msg_to = email

    content = """
    慕慕手记注册验证码是：<p style='color:red;'>{}</p>
    """.format(code)

    # msg = MIMEText(content)
    msg = MIMEMultipart()
    msg['Subject'] = '慕慕手记验证码'
    msg['From'] = '=?utf-8?B?' + base64.b64encode('慕慕手记'.encode('utf-8')).decode('utf-8') + '?= <321459055@qq.com>'
    msg['To'] = msg_to
    msg.attach(MIMEText(content, 'html', 'utf-8'))

    s = smtplib.SMTP_SSL('smtp.qq.com', 465)
    s.login(email_name, passwd)
    s.sendmail(email_name, msg_to, msg.as_string())
